package com.client.core.handler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.client.core.service.ChatService;
import com.client.core.service.FileRec;
import com.client.core.service.FileSend;
import com.client.core.service.FileStart;
import com.common.GZipUtils;
import com.common.Msg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ActionHandler extends SimpleChannelInboundHandler<Msg> {

    private ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 文件交换业务
     *
     * @param channelHandlerContext
     * @param res
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Msg res) throws Exception {

        switch (res.getType()) {

            case REC_GROUP:
                //接收群列表数据
                byte[] ungzip = GZipUtils.ungzip(res.getBytes());
                String s = new String(ungzip);
                JSONArray objects = JSON.parseArray(s);
                ChatService.groups = objects;
                break;
            case REC_MSG:
                byte[] rec_msg = GZipUtils.ungzip(res.getBytes());
                System.out.println("(" + res.getHe() + ")发来消息->" + new String(rec_msg));
            case OK_FILE:
                //给别人发文件，别人给我我们回复的消息，
                byte[] ok_msg = GZipUtils.ungzip(res.getBytes());
                System.out.println("(" + res.getHe() + ")发来成功发送一个分片文件消息->" + new String(ok_msg));
                //通过消息，查看当前文件是否发生完成，没有完成就继续给他发文件消息
            case REC_FILE:
                //接收到别人发来的文件消息，然后进行存储
                executorService.submit(new FileRec(res));
                break;
            case START_FILE:
                //首次发送文件，读取当前文件夹，获取应该需要什么文件
                byte[] start_msg = GZipUtils.ungzip(res.getBytes());
                String s1 = new String(start_msg);
                System.out.println("(" + res.getHe() + ")发来文件拆分说明消息->" + new String(s1));
                //线程池里面去执行相关的检查，和文件发送
                executorService.submit(new FileStart(s1));
                break;
            case REQ_FILE:
                //这个是别人发来的文件请求，更具文件内容来获取文件吧
                String s2 = new String(GZipUtils.ungzip(res.getBytes()));
                System.out.println("(" + res.getHe() + ")发来文件请求->" +s2);
                executorService.submit(new FileSend(s2));
        }
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
